package com.homework.test02;

import java.io.*;
import java.util.Scanner;

/**
 * @author south wind
 * @version 1.0
 * @date 2025/4/7 19:20
 * @description  复制文件夹以及文件夹下的文件，一层   拓展：多层
 */
public class CopyFile {
    public static final Scanner input = new Scanner(System.in);

    public static void CopyFolder(File sourceFile , File targetFile){
        if (!sourceFile.exists()){
            System.err.println("源文件不存在！");
            return;
        }
        if (!targetFile.exists()){
            targetFile.mkdirs();
        }

        File[] files = sourceFile.listFiles();
        if ( files != null){
            for (File file : files) {
                if (file.isFile()){
                    try {
                        FileInputStream fis = new FileInputStream(file);
                        FileOutputStream fos = new FileOutputStream(new File(targetFile,file.getName()));
                                byte[] bytes = new byte[1024];
                        int len =0;
                        while ((len = fis.read(bytes)) != -1){
                            fos.write(bytes,0,len);
                        }

                    } catch (FileNotFoundException e) {
                        e.printStackTrace();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                else if (file.isDirectory()){
                    File newTargetFile = new File(targetFile,file.getName());
                    CopyFolder(file,newTargetFile);
                }
            }
        }
        System.out.println("多层复制完成！");
    }

    public static void main(String[] args) {
        System.out.println("请输入源文件夹：");
        String source = input.next();
        File sourceFile = new File(source);

        System.out.println("请输入目标文件夹：");
        String target = input.next();
        File targetFile = new File(target);

        CopyFolder(sourceFile,targetFile);
    }
}
